<template>
  <div style="padding: 15px;">
    <vxe-toolbar id="warehouseLocationId" :custom="{storage: true}" export :refresh="{query: findList}">
      <template v-slot:buttons>
        <el-button @click="findList">查询</el-button>
        <el-button @click="start">指派</el-button>
        <el-button @click="block">取消</el-button>

      </template>
    </vxe-toolbar>
    <vxe-table
      ref="xTable"
      border
      resizable
      stripe
      highlight-current-row
      :export-config='{type:"csv"}'
      show-footer
      highlight-hover-row
      row-id="id"
      class="mytable-footer"
      align="center"
      height="700"
      :loading="loading"
      :data="tableData"
      :edit-config="{trigger: 'click', mode: 'row', showStatus: true}"
      sort-config.remote
      @sort-change="sortList"
      :seq-config="{startIndex: listQuery.pageNum * listQuery.pageSize - listQuery.pageSize}"
    >
      <vxe-table-column type="seq" width="60"></vxe-table-column>
      <vxe-table-column type="checkbox" width="60"></vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="assign" title="状态" min-width="100" sortable show-header-overflow show-overflow
                          :formatter="formatterStatus"/>
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.assign" placeholder="请选择状态" clearable>
            <el-option value="0" label="待指派"/>
            <el-option value="1" label="已指派"/>
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="jobStatus" title="作业状态" min-width="100" sortable show-header-overflow show-overflow
                          :formatter="formatterJobStatus"/>
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.jobStatus" placeholder="请选择状态" clearable>
            <el-option value="WAITING" label="待作业"/>
            <el-option value="WORKING" label="作业中"/>
            <el-option value="COMPLETED" label="作业完成"/>
          </el-select>
        </template>
      </vxe-table-column>

      <vxe-table-column>
        <vxe-table-column field="code" title="任务号" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.code" placeholder="请输入任务号" clearable/>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="taskType" title="任务类型" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.taskType" placeholder="请选择任务类型" clearable>
            <el-option value="RECEIVE" label="收货"/>
            <el-option value="PUTAWAY" label="上架"/>
            <el-option value="PICKING" label="拣货"/>
            <el-option value="CHECK" label="复核"/>
            <el-option value="INVENTORY" label="盘点"/>
            <el-option value="MOVE" label="移位"/>
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="sourceCode" title="关联单号" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.sourceCode" placeholder="请输入关联单号" clearable/>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="goodsTypeQuantity" title="商品种数" min-width="200" sortable/>
        <template v-slot:header="{ column }">
          <el-input type="number" min="0"  v-model="listQuery.goodsTypeQuantityLow" placeholder="下限" style="width:45%;"/>
          -
          <el-input type="number" min="0"  v-model="listQuery.goodsTypeQuantityUp" placeholder="上限" style="width:80px;"/>
        </template>
      </vxe-table-column>


      <vxe-table-column>
        <vxe-table-column field="goodsQuantity" title="商品件数" min-width="200" sortable/>
        <template v-slot:header="{ column }">
          <el-input type="number" min="0"   v-model="listQuery.goodsQuantityLow" placeholder="下限" style="width:80px;"/>
          -
          <el-input type="number" min="0"  v-model="listQuery.goodsQuantityUp" placeholder="上限" style="width:80px;"/>
        </template>
      </vxe-table-column>

      <vxe-table-column>
        <vxe-table-column field="jobQuantity" title="作业件数" min-width="200" sortable/>
        <template v-slot:header="{ column }">
          <el-input type="number"  min="0" v-model="listQuery.jobQuantityLow" placeholder="下限" style="width:80px;"/>
          -
          <el-input type="number" min="0"  v-model="listQuery.jobQuantityUp" placeholder="上限" style="width:80px;"/>
        </template>
      </vxe-table-column>


      <vxe-table-column>
        <vxe-table-column field="operatorName" title="作业人" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.operatorName" placeholder="请输入作业人" clearable/>
        </template>
      </vxe-table-column>

      <vxe-table-column>
        <vxe-table-column field="createdName" title="创建人" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.createdName" placeholder="请输入创建人" clearable/>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="gmtCreated"
          show-header-overflow
          show-overflow
          title="创建时间"
          min-width="420"
          sortable
          :resizable="false"
        />
        <template v-slot:header>
          <el-date-picker
            v-model="gmtCreatedRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"

            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="value => changeDate(value, 'gmtCreated')"
          />
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column field="assignName" title="指派人" min-width="150" sortable/>
        <template v-slot:header="{ column }">
          <el-input v-model="listQuery.assignName" placeholder="请输入指派人" clearable/>
        </template>
      </vxe-table-column>
      <vxe-table-column>
        <vxe-table-column
          field="gmtModified"
          show-header-overflow
          show-overflow
          title="指派时间"
          min-width="420"
          sortable
          :resizable="false"
        />
        <template v-slot:header>
          <el-date-picker
            v-model="gmtModifiedRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            style="width:100%"
            range-separator="至"

            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="value => changeDate(value, 'gmtModified')"
          />
        </template>
      </vxe-table-column>

      <!-- <vxe-table-column>
        <vxe-table-column field="warehouseCode" :formatter="formatterStatus" title="所属仓库" min-width="100" sortable />
        <template v-slot:header="{ column }">
          <el-select v-model="listQuery.warehouseCode" placeholder="请选择所属仓库" @change="findtasksList" style="width: 100%">
            <el-option v-for="item in warehouseList" :key="item.code" :label="item.name" :value="item.code" />
          </el-select>
        </template>
      </vxe-table-column> -->
      <vxe-table-column title="操作" fixed="right" min-width="150">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="详情" placement="top">
            <vxe-button type="text" @click="funcDetail(scope.row.code)">
              <i class="el-icon-document"/>
            </vxe-button>
          </el-tooltip>

        </template>
      </vxe-table-column>
    </vxe-table>
    <vxe-pager
      :loading="loading"
      :current-page.sync="listQuery.pageNum"
      :page-size.sync="listQuery.pageSize"
      :total="listQuery.total"
      :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
      @page-change="handlePageChange"
    />

    <vxe-modal v-model="modelAuditFlag" title="指派" width="500" height="200">
      <compAudit ref="auditRef" @fatherAudit="fatherAudit"/>
    </vxe-modal>

  </div>
</template>
<script>
  import Vue from 'vue'
  import 'xe-utils'
  import VXETable from 'vxe-table'
  import 'vxe-table/lib/index.css'
  import XEUtils from 'xe-utils'
  import VXEUtils from 'vxe-utils'

  Vue.use(VXETable, VXEUtils, XEUtils, {mounts: ['cookie']})
  import request from '@/utils/request'
  import compAudit from "./components/tasksAssign.vue";

  import {tasksList, tasksAssign, tasksUnAssign} from '@/api/store'

  export default {
    name: '任务中心',
    components: {
      compAudit
    },
    data() {
      return {
        party: this.$store.getters.party,
        pickerOptions: {
          shortcuts: [
            {
              text: "最近一周",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "最近一个月",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit("pick", [start, end]);
              }
            },
            {
              text: "最近三个月",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit("pick", [start, end]);
              }
            }
          ]
        },

        message: '',
        loading: false,
        tableData: [],
        modelAddFlag: false,
        modelbindingFlag: false,
        modelEditFlag: false,
        modelDetailFlag: false,
        modelAuditFlag: false,
        staffs: [],
        gmtCreatedRange: "",
        gmtModifiedRange: "",
        copy: false,
        listQuery: {

          code: '',              //数据标识 ,
          name: '',              //类型名称 ,
          num: '',               //数量 ,
          taskType: '',
          jobStatus: '',
          sourceCode: '',          //托盘数量 ,
          remarks: '',           //备注 ,
          skuQuantity: '',       //SKU数量 ,
          assign: '',            //状态 ,
          total: '',             //总数 ,
          jobQuantity: '',            //体积 ,
          jobQuantityUp: '',            //体积 ,
          jobQuantityLow: '',            //体积 ,
          goodsQuantity: '',            //重量
          goodsQuantityUp: '',            //重量
          goodsQuantityLow: '',            //重量

          goodsTypeQuantity: "",
          goodsTypeQuantityUp: '',
          goodsTypeQuantityLow: '',
          total: 0,             //总数
          createdBy: '',         //创建人
          createdName: '',         //创建人
          operatorName: '',
          modifiedBy: '',        //修改人
          assignName: '',        //修改人
          gmtCreated: '',        //创建时间
          gmtModified: '',       //修改时间

          pageNum: 1,
          pageSize: 10,
          sortField: '',
          sortType: '',
        },
      }
    },
    created() {
      this.findList()
    },
    methods: {
      findStaffs() {
        request({
          url: '/arpa-basic-api/staffs/chooseData',
          method: 'get',
          params: {branchCode: this.party.branchCode}
        }).then(response => {
          this.staffs = response.data
          this.$refs.auditRef.userData = this.staffs
        })
      },

      //指派
      start() {
        this.findStaffs()
        let selectRecords = this.$refs.xTable.getCheckboxRecords()
        let arr = []
        selectRecords.forEach(i => {
          arr.push(i.code)
        })
        arr = arr.join(",");
        if (arr.length != 0) {
          this.$refs.auditRef.arr = arr
          this.$refs.auditRef.reset();    //重置


          this.modelAuditFlag = true;

        } else {
          this.$message('没有能指派的数据！')
        }
      },
      // 指派父方法
      fatherAudit() {
        this.modelAuditFlag = false;
        this.findList();
      },

      //取消指派
      block() {
        let selectRecords = this.$refs.xTable.getCheckboxRecords()
        let arr = []
        selectRecords.forEach(i => {
          arr.push(i.code)
        })
        arr = arr.join(",");
        if (arr.length != 0) {
          this.$confirm('确认取消指派吗？').then(_ => {
            tasksUnAssign(arr).then(response => {
              this.$message({dangerouslyUseHTMLString: true, message: response.msg, type: 'success'})
              this.findList()
            })
          }).catch(_ => {
          })
        } else {
          this.$message('没有能取消指派的数据！')
        }
      },
      // 翻译状态
      formatterStatus({cellValue}) {
        if (cellValue == '0') {
          return '待指派'
        } else if (cellValue == '1') {
          return '已指派'
        }
      },
      formatterJobStatus({cellValue}) {
        if (cellValue === 'WAITING') {
          return '待作业'
        }
        if (cellValue === 'WORKING') {
          return '作业中'
        }
        if (cellValue === 'COMPLETED') {
          return '作业完成'
        }
      },
      //获取列表
      findList() {
        this.loading = true
        return tasksList(this.listQuery).then(response => {
          this.tableData = response.data.records
          this.listQuery.total = response.data.total
          this.loading = false
        })
      },
    changeDate(value, prefix) {
      if (value) {
        this.listQuery[`${prefix}Start`] = value[0] + " 00:00:00";
        this.listQuery[`${prefix}End`] = value[1] + " 23:59:59";
      } else {
        this.listQuery[`${prefix}Start`] = "";
        this.listQuery[`${prefix}End`] = "";
      }
    },

      // 排序
      sortList({column, property, order}) {
        if (order) {
          this.listQuery.sortField = property
          this.listQuery.sortType = order
        } else {
          this.listQuery.sortField = ''
        }
        this.findList()
      },
      // 详情方法
      funcDetail(code) {
        this.$router.push({
          path: "/zhcx/tasksDetail",
          query: {code: code},
        });
      },
      // 公共取消
      fatherCancel(modelFlag) {
        switch (modelFlag) {
          case 'add':
            this.modelAddFlag = false
            break
          case 'edit':
            this.modelEditFlag = false
            break
          case 'detail':
            this.modelDetailFlag = false
            break
          default:
        }
      },
      // 分页handle
      handlePageChange({currentPage, pageSize}) {
        this.listQuery.pageNum = currentPage
        this.listQuery.pageSize = pageSize
        this.findList()
      },
      // 底部颜色设置
      /*  footerCellClassName({ $rowIndex, column, columnIndex }) {
         if (columnIndex === 0) {
           if ($rowIndex === 0) {
             return 'col-blue'
           } else {
             return 'col-red'
           }
         }
       }, */
      // 设置底部合计
      footerMethod({columns, data}) {
        return [
          columns.map((column, columnIndex) => {
            if (columnIndex === 0) {
              return '合计'
            }
            if (['pageviews', 'forecast'].includes(column.property)) {
              return XEUtils.sum(data, column.property)
            }
            return null
          })
        ]
      }
    }
  }
</script>

<style>
  .vxe-table .vxe-body--column:not(.col--ellipsis), .vxe-table .vxe-footer--column:not(.col--ellipsis), .vxe-table .vxe-header--column:not(.col--ellipsis) {
    padding: 6px 0;
  }

  .vxe-toolbar {
    padding: 0 0 10px 0
  }
</style>
